package com.example.config.security;

import com.example.entity.Requesturl;
import com.example.entity.Role;
import com.example.mapper.RequesturlMapper;
import com.example.service.IRequesturlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IRequesturlService iRequesturlService;
    @Autowired
    private RequesturlMapper requesturlMapper;

    AntPathMatcher antPathMatcher = new AntPathMatcher();



    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation)o).getRequestUrl();
//        System.out.println("requestUrl is "+requestUrl);
        List<Requesturl> requesturls = iRequesturlService.getUrlWithRole();

        for(Requesturl requesturl:requesturls){
//            System.out.println("requesturlMapper.getRoles is "+requesturlMapper.getRoles(requesturl.getId()).get(0));
            requesturl.setRoles(requesturlMapper.getRoles(requesturl.getId()));
//            System.out.println("requesturl is "+requesturl.getUrl());
            if(antPathMatcher.match(requesturl.getUrl(),requestUrl)){
//                System.out.println("antPathMatcher.match(requesturl.getUrl(),requestUrl):"+antPathMatcher.match(requesturl.getUrl(),requestUrl));
//                System.out.println("requesturl.getRoles() is "+requesturl);
                String[] strings = requesturl.getRoles().stream().map(Role::getName).toArray(String[]::new);

                return SecurityConfig.createList(strings);
            }
        }
        //没有匹配的url
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
